﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UIT.Commands
{
    public class CommandManager : ICommandBuilder
    {
        Dictionary<string, Type> registeredCommands = new Dictionary<string, Type>();

        public void RegisterCommand<T>(string name)
            where T : ICommand
        {
            registeredCommands.Add(name, typeof(T));
        }

        public ICommand GetCommand(string name)
        {
            return (ICommand)Activator.CreateInstance(registeredCommands[name]);
        }

        public IEnumerable<CommandMetadata> GetCommands(string pattern)
        {
            IEnumerable<CommandMetadata> commandTypes = registeredCommands.Select(kvp => new CommandMetadata { Name = kvp.Key, CommandType = kvp.Value });

            if (pattern == "*")
                return commandTypes;

            if (pattern.IndexOf('*') == pattern.Length - 1)
            {
                pattern = pattern.Substring(0, pattern.Length - 1);
                commandTypes = commandTypes.Where(cm => cm.Name.StartsWith(pattern));
            }
            else if (pattern.LastIndexOf('*') == 0)
            {
                pattern = pattern.Substring(1, pattern.Length - 1);
                commandTypes = commandTypes.Where(kvp => kvp.Name.EndsWith(pattern));
            }
            else
                commandTypes = commandTypes.Where(cm => cm.Name.Contains(pattern));

            return commandTypes;
        }
    }
}
